import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'

const STORAGE_KEY = 'note-app-data'
const SELECTED_TAG_KEY = 'note-app-selected-tag'

export const useNoteStore = defineStore('note', () => {
  // 从localStorage加载初始数据
  const loadFromStorage = () => {
    const savedData = localStorage.getItem(STORAGE_KEY)
    if (savedData) {
      const { tags: savedTags, notes: savedNotes } = JSON.parse(savedData)
      tags.value = savedTags || []
      notes.value = savedNotes || []
    }
    
    // 加载选中的标签ID
    const savedSelectedTag = localStorage.getItem(SELECTED_TAG_KEY)
    if (savedSelectedTag) {
      selectedTagId.value = savedSelectedTag
    }
  }
  
  // 保存数据到localStorage
  const saveToStorage = () => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify({
      tags: tags.value,
      notes: notes.value
    }))
  }
  
  const tags = ref([])
  const notes = ref([])
  const selectedTagId = ref('all')
  
  // 监听选中的标签变化并保存
  watch(selectedTagId, (newVal) => {
    localStorage.setItem(SELECTED_TAG_KEY, newVal)
  })
  const searchQuery = ref('')
  
  // 初始化时加载数据
  loadFromStorage()

  // 计算属性
  const filteredNotes = computed(() => {
    let filtered = notes.value
    
    // 按标签过滤
    if (selectedTagId.value !== 'all') {
      filtered = filtered.filter(note => note.tagId === selectedTagId.value)
    }
    
    // 按搜索查询过滤
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      filtered = filtered.filter(note => 
        note.content.toLowerCase().includes(query)
      )
    }
    
    return filtered
  })

  const tagCounts = computed(() => {
    const counts = { all: notes.value.length }
    tags.value.forEach(tag => {
      counts[tag.id] = notes.value.filter(note => note.tagId === tag.id).length
    })
    return counts
  })

  // 方法
  function addTag(name) {
    const newTag = {
      id: Date.now().toString(),
      name
    }
    tags.value.push(newTag)
    saveToStorage()
    return newTag
  }

  function updateTag(id, newName) {
    const tag = tags.value.find(t => t.id === id)
    if (tag) {
      tag.name = newName
      saveToStorage()
    }
  }

  function deleteTag(id) {
    // 先删除该标签下的所有笔记
    notes.value = notes.value.filter(note => note.tagId !== id)
    // 然后删除标签
    tags.value = tags.value.filter(tag => tag.id !== id)
    saveToStorage()
  }

  function addNote(tagId = null, afterNoteId = null) {
    const newNote = {
      id: `note-${Date.now()}`,
      tagId: tagId || selectedTagId.value,
      content: '',
      color: '#E0F7FA', // 默认薄荷绿色
      createTime: new Date().toISOString()
    }
    
    if (afterNoteId) {
      const index = notes.value.findIndex(note => note.id === afterNoteId)
      if (index !== -1) {
        notes.value.splice(index + 1, 0, newNote)
      } else {
        notes.value.push(newNote)
      }
    } else {
      notes.value.push(newNote)
    }
    
    saveToStorage()
    return newNote
  }

  function updateNote(id, updates) {
    const note = notes.value.find(n => n.id === id)
    if (note) {
      Object.assign(note, updates)
      saveToStorage()
    }
  }

  function deleteNote(id) {
    notes.value = notes.value.filter(note => note.id !== id)
    saveToStorage()
  }

  function reorderNotes(newOrder) {
    notes.value = newOrder
    saveToStorage()
  }

  return {
    tags,
    notes,
    selectedTagId,
    searchQuery,
    filteredNotes,
    tagCounts,
    addTag,
    updateTag,
    deleteTag,
    addNote,
    updateNote,
    deleteNote,
    reorderNotes
  }
})